

const fs = require('fs-extra');
const path = require('path');
const { nativeImage } = require('electron');
const { translate } = require('../pinyinUtil');
const { put, get } = require('../levelDbUtil');
const dbConstance = require('../../constans/dbKeyConstans')


const { APP_FINDER_PATH } = require('../../constans/pathConstans');
const { bpList } = require('bplist-parser');
const { iconvLite } = require('iconv-lite');
const { Module } = require('module');



const isZhRegex = /[\u4e00-\u9fa5]/;
const getDisplayNameRegex = /\"?(?:CFBundleDisplayName)\"?\s\=\s\"(.*)\"/;





function getAppZhNameByDisplay(appInfoPath) {
    let appZhName = '';
    let fileContent = fs.readFileSync(appInfoPath);
    if (fileContent) {
        // 解析为utf8或者utf16
        let contentWithUtf16 = iconvLite.decode(fileContent, 'utf-16');
        let contentWithUtf8 = iconvLite.decode(fileContent, 'utf-8');

        contentWithUtf16 = contentWithUtf16.match(getDisplayNameRegex);
        contentWithUtf8 = contentWithUtf8.match(getDisplayNameRegex);
        appZhName = (contentWithUtf16 && contentWithUtf16[1]) || (contentWithUtf8 && contentWithUtf8[1]);
    }

    return appZhName;
}


async function getAppZhName(rootPath, appName) {
    try {
        const ERROR_RESULT = '';
        const systemPath = path.join(rootPath, `${appName}/Contents/Resources/zh_CN.lproj/InfoPlist.strings`);
        const customizePath = path.join(rootPath, `${appName}/Contents/Resources/zh-Hans.lproj/InfoPlist.strings`);
        let appInfoPath = '';

        if (fs.existsSync(systemPath)) {
            appInfoPath = systemPath;
        } else if (fs.existsSync(customizePath)) {
            appInfoPath = customizePath;
        } else {
            return ERROR_RESULT;
        }
        let appZhName = '';
        if (rootPath == '/Applications') {
            appZhName = getAppZhNameByDisplay(appInfoPath);
        } else {
            const [{ CFBundleDisplayName = '', CFBundleName = '' }] = await bpList.parseFile(appInfoPath);
            appZhName = CFBundleDisplayName || CFBundleName;
        }

        return appZhName;
    } catch (error) {
        return ERROR_RESULT;
    }
}


async function updateDarwinAppList() {
    let fileLists = [];
    for (i in APP_FINDER_PATH) {
        try {
            searchPath = APP_FINDER_PATH[i]
            files = fs.readdirSync(searchPath)
            for (let i = 0; i < files.length; i++) {
                const appName = files[i];
                const blackList = ['.localized', '.DS_Store']
                if (blackList.indexOf(appName) != -1) {
                    continue
                }
                const extname = path.extname(appName);
                const appSubStr = appName.split(extname)[0];

                if ((extname === '.app' || extname === '.prefPane') >= 0) {
                    try {
                        const path1 = path.join(searchPath, `${appName}/Contents/Resources/App.icns`);
                        const path2 = path.join(searchPath, `${appName}/Contents/Resources/AppIcon.icns`);
                        const path3 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr}.icns`);
                        const path4 = path.join(searchPath, `${appName}/Contents/Resources/${appSubStr.replace(' ', '')}.icns`);
                        let iconPath = path1;
                        if (fs.existsSync(path1)) {
                            iconPath = path1;
                        } else if (fs.existsSync(path2)) {
                            iconPath = path2;
                        } else if (fs.existsSync(path3)) {
                            iconPath = path3;
                        } else if (fs.existsSync(path4)) {
                            iconPath = path4;
                        } else {
                            // 性能最低的方式
                            const resourceList = fs.readdirSync(path.join(searchPath, `${appName}/Contents/Resources`));
                            const iconName = resourceList.filter((file) => path.extname(file) === '.icns')[0];
                            iconPath = path.join(searchPath, `${appName}/Contents/Resources/${iconName}`);
                        }
                        const img = await nativeImage.createThumbnailFromPath(iconPath, { width: 64, height: 64 });

                        const appZhName = await getAppZhName(searchPath, appName);

                        const fileOptions = {
                            value: 'plugin',
                            icon: img.toDataURL(),
                            desc: path.join(searchPath, appName),
                            type: 'app',
                            action: `open ${path.join(searchPath, appName).replace(' ', '\\ ')}`,
                            keyWords: [appSubStr],
                        };

                        if (appZhName && isZhRegex.test(appZhName)) {
                            const py = translate(appZhName);
                            const pinyinArr = py.split(',');
                            const firstLatter = pinyinArr.map((py) => py[0]);
                            // 拼音
                            fileOptions.keyWords.push(pinyinArr.join(''));
                            // 缩写
                            fileOptions.keyWords.push(firstLatter.join(''));
                            // 中文
                            fileOptions.keyWords.push(appZhName);
                        }

                        fileLists.push({
                            ...fileOptions,
                            name: appSubStr,
                            names: JSON.parse(JSON.stringify(fileOptions.keyWords)),
                        });
                    } catch (e) {
                    }
                }
            }
        } catch (e) { }
    }
    put(dbConstance.SYS_APP_LIST, JSON.stringify(fileLists))

}

async function getDarwinAppList() {
    try {
        const data = await get(dbConstance.SYS_APP_LIST)
        return data._data
    } catch (e) {
        return []
    }

}



module.exports = {
    getDarwinAppList,
    updateDarwinAppList
}